package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.service.IOrganizationService;
import com.xmy.cultivate.service.IStaffService;
import com.xmy.cultivate.service.ITrackDetailService;
import com.xmy.cultivate.service.ITrackService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author min
 * @since 2022-12-27
 */
@RestController
@RequestMapping("/api/track")
public class TrackController extends BaseController{

    @Autowired
    ITrackService iTrackService;

    @Autowired
    IStaffService iStaffService;

    @Autowired
    ITrackDetailService iTrackDetailService;

    @Autowired
    IOrganizationService iOrganizationService;


    @GetMapping()
    public Result findAll(@RequestParam Map<String,String> reMap){

        Integer pageNum = StringUtils.isEmpty(reMap.get("pageNum")) ? 1 : Integer.valueOf(reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty(reMap.get("pageSize")) ? 10: Integer.valueOf(reMap.get("pageSize"));
        IPage<Track> iPage = new Page<>(pageNum,pageSize);
        String name = reMap.get("name");
        String classify = reMap.get("classify");//分类：分类：1是续班赛道，2是招生赛道
        if(StringUtils.isEmpty(classify)){
            classify = "1";
        }

        String yearPart  = null;
        if (reMap.get("yearPart") != null && !reMap.get("yearPart").isEmpty()) {
            yearPart  = reMap.get("yearPart");
        }
        String quarterNum  = null;
        if (reMap.get("quarterNum") != null && !reMap.get("quarterNum").isEmpty()) {
            quarterNum  = reMap.get("quarterNum");
        }

        QueryWrapper<Track> queryWrapper =  new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name),"name",name);
        queryWrapper.eq("classify",classify);
        queryWrapper.eq("deleted",0);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.orderByAsc("sort,id");
        iTrackService.page(iPage,queryWrapper);
        return new Result(Code.OK,new PageResult(iPage.getRecords(),iPage.getTotal(),iPage.getPages()));
    }


    @GetMapping(value = "/{id}",name = "course:findbyid")
    public Result findById(@PathVariable(value = "id") Long id){
        System.out.print("findById");
        Track track = iTrackService.getById(id);
        return new Result(Code.OK,track);
    }

    @PostMapping()
    public Result save(@RequestBody Track track){
        iTrackService.save(track);
        //System.out.println(course);
        return new Result(Code.OK);
    }

    @PutMapping("/{id}")
    public Result update(@PathVariable(value = "id") String id,@RequestBody Track track){

        iTrackService.updateById(track);
        return new Result(Code.OK);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable(value = "id") Long id){
        boolean rs =  iTrackService.removeById(id);
        return new Result(rs?Code.OK:Code.ERROR);
    }

    @PostMapping("/addBatchSourse")
    public Result addBatchSourse(@RequestBody Track track){
        boolean rs =  iTrackService.addBatchSourse(track);
        return new Result(rs?Code.OK:Code.ERROR);
    }

    @DeleteMapping("/deleteBatchSourse")
    public Result deleteBatchSourse(@RequestBody Track track){
        boolean rs = iTrackDetailService.removeBatchByIds(track.getSourseIdList());
        return new Result(rs?Code.OK:Code.ERROR);
    }


    /**
     *
     * @param reMap
     * @param schoolIdList
     * @param isRepetition 是否允许重复
     * @return
     */
    @GetMapping("checkTeacher")
    public Result checkTeacher(@RequestParam Map<String,String> reMap,
                               @RequestParam(value = "schoolIdList",defaultValue = "") String[] schoolIdList,
                               @RequestParam(value = "isRepetition",required = false) String isRepetition){
        Integer pageNum = StringUtils.isEmpty((String)reMap.get("pageNum")) ? 1 : Integer.valueOf((String)reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String)reMap.get("pageSize")) ? 1000: Integer.valueOf((String)reMap.get("pageSize"));

        IPage<Staff> page = new Page<>(pageNum,pageSize);
        //String schoolId = (String) reMap.get("schoolId");//管辖校区

        String isTeacher = "1";
        String status = "1";

        String trackId = (String) reMap.get("trackId");
        String type = (String) reMap.get("type");// 1校长 2老师（新老师、老老师）

        QueryWrapper<Staff> staffQueryWrapper =  new QueryWrapper<>();
        //staffQueryWrapper.eq(StringUtils.isNotBlank(isTeacher),"is_teacher",isTeacher);
        staffQueryWrapper.eq(StringUtils.isNotBlank(status),"status",status);

        if(schoolIdList.length > 0){
            String schoolIdStr = String.join(",", schoolIdList);
            //staffQueryWrapper.and(i->i.eq("scope_class_mode",1).or().inSql("id","select for_id from appoint_school where type=4 and school_id in("+schoolIdStr+")"));
            staffQueryWrapper.in("school_id",schoolIdStr);

        }else {
            //System.out.print("baseSchoolIdStr:"+baseSchoolIdStr);
            //staffQueryWrapper.and(i->i.eq("scope_class_mode",1).or().inSql("id","select for_id from appoint_school where type=4 and school_id in("+this.baseSchoolIdStr+")"));
            //staffQueryWrapper.in("school_id",this.baseSchoolIdStr);
        }

        String name = (String) reMap.get("name");
        if(StringUtils.isNotBlank(name)){
            staffQueryWrapper.like("name",name);
        }

        if(StringUtils.isNotBlank(trackId)){
            Track trackInfo = iTrackService.getById(trackId);
            if (trackInfo == null){
                return new Result(Code.ERROR,"","赛道不存在");
            }
            if (StringUtils.isNotBlank(isRepetition) && isRepetition.equals("1")){
                staffQueryWrapper.notInSql("id","select sourse_id from track_detail where type = "+trackInfo.getType()+" and deleted=0 and classify="+trackInfo.getClassify()+" and track_id="+trackInfo.getId());
            }else {
                staffQueryWrapper.notInSql("id","select sourse_id from track_detail where type = "+trackInfo.getType()+" and deleted=0 and classify="+trackInfo.getClassify()+"");
            }
        }

        if (StringUtils.isNotBlank(type)) {
            if (type.equals("1")) {// 校长
                staffQueryWrapper.inSql("id","select admin_id from role_admin where role_id = 1568160887369994242");
            } else if (type.equals("2")) {// 新老师、老老师
                staffQueryWrapper.inSql("id","select admin_id from role_admin where role_id in ( 1568160855895937026,1568160855895937096)");
            }
        }

        //staffQueryWrapper.eq(StringUtils.isNotBlank(schoolId),"school_id",schoolId);

        iStaffService.findAll(page,staffQueryWrapper);

        return new Result(Code.OK,new PageResult(page.getRecords(),page.getTotal(),page.getPages()));
    }

    @GetMapping("checkSchool")
    public Result checkSchool(@RequestParam Map reMap){
        Integer pageNum = StringUtils.isEmpty((String)reMap.get("pageNum")) ? 1 : Integer.valueOf((String)reMap.get("pageNum"));
        Integer pageSize = StringUtils.isEmpty((String)reMap.get("pageSize")) ? 1000: Integer.valueOf((String)reMap.get("pageSize"));

        IPage<Organization> page = new Page<>(pageNum,pageSize);
        //String schoolId = (String) reMap.get("schoolId");//管辖校区

        String trackId = (String) reMap.get("trackId");

        QueryWrapper<Organization> organizationQueryWrapper =  new QueryWrapper<>();

        String name = (String) reMap.get("name");
        if(StringUtils.isNotBlank(name)){
            organizationQueryWrapper.like("name",name);
        }

        if(StringUtils.isNotBlank(trackId)){
            organizationQueryWrapper.notInSql("id","select sourse_id from track_detail where type = 2 and deleted=0 and track_id="+trackId+"");
        }

        organizationQueryWrapper.eq("type",1);
        //staffQueryWrapper.eq(StringUtils.isNotBlank(schoolId),"school_id",schoolId);

        iOrganizationService.page(page,organizationQueryWrapper);

        return new Result(Code.OK,new PageResult(page.getRecords(),page.getTotal(),page.getPages()));
    }

}
